package com.tzy.shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzy.common.constant.WebResult;
import com.tzy.common.constant.WebResultMsgCode;
import com.tzy.common.controller.BaseController;
import com.tzy.common.entity.Shop;
import com.tzy.shop.service.IShopService;
import com.tzy.shop.service.RedisService;
import com.tzy.shop.utils.UpFilesNameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商家店铺表 前端控制器
 * </p>
 *
 * @author ljh
 * @since 2022-03-01
 */
@RestController
@RequestMapping("/shop")
public class ShopController extends BaseController {

	private Logger log = LoggerFactory.getLogger("ShopLog");
	@Resource
	private IShopService iShopService;
	@Resource
	private RedisService redisService;

	//文件上传路径
	@Value("${file.upload.url}")
	private String uploadUrl;
	//服务器路径前缀
	@Value("${file.upload.prefix-url}")
	private String prefixUrl;
	//默认头像路径
	@Value("${file.upload.default-profile-photo}")
	private String defaultProfilePhoto;

	/**
	 * 查询店铺
	 * 除了类型为冻结状态的店铺其他的全部显示
	 */
	@GetMapping("/list")
	@Cacheable(value = "shop_List", unless = "#request == null ")
	public WebResult shopList(){
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("state",2);
		List<Shop> list = iShopService.list();
		return new WebResult(WebResultMsgCode.SUCCESS,list);
	}

	/**
	 * 根据评分倒叙查询店铺
	 * @return
	 */
	@GetMapping("/listChoicenessShop")
	@Cacheable(value = "list_choiceness_shop", unless = "#request == null ")
	public WebResult listChoicenessShop(){
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("grade");
		List<Shop> list = iShopService.list(queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("list", list);
	}

	/**
	 * 查询类型为冻结的店铺
	 * @return
	 */
	@GetMapping("/listAuditShop")
	@Cacheable(value = "list_audit_shop", unless = "#request == null ")
	public WebResult listAuditShop(){
		//查询待审核的店铺信息
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<Shop>();
		queryWrapper.eq("state","2");
		List<Shop> listShop = iShopService.list(queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("shop", listShop);
	}

	/**
	 * 添加店铺
	 * @param shop
	 * @return
	 */
	@PostMapping("/addShop")
	public WebResult addShop(HttpServletRequest request, Shop shop){
		//获取前端传过来的店铺信息将店铺信息存到数据库
		log.info("shop:"+shop);
		int userId = getUserId(request);
		shop.setUserId(userId);
		shop.setState("2");
		//获取当前系统时间
		LocalDateTime dateTime = LocalDateTime.now();
//		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
//		System.out.println();
//		System.out.println("当前系统时间："+dateTime.format(formatter));
//		shop.setShopTime(LocalDateTime.parse(dateTime.format(formatter)));
		boolean judge = iShopService.addShop(shop);
		log.info("judge:"+judge);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("judge", judge);
	}

	/**
	 * 根据店铺ID修改店铺
	 * @param shop 店铺集合
	 * @return
	 */
	@PostMapping("/updateShop")
	public WebResult updateShop(Shop shop){
		//获取前端传过来需要修改的店铺数据将数据库里面的信息进行修改返回Boolean类型
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", shop.getId());
		boolean judge = iShopService.update(shop,queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("judge", judge);

	}

	/**
	 * 删除店铺
	 * @return
	 */
	@PostMapping("/deleteShop")
	public WebResult deleteShop(Integer shopId){
		log.info("shopId:"+shopId);
		//获取前端传过来的店铺ID然后进行删除
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", shopId);
		boolean judge = iShopService.remove(queryWrapper);
		log.info("judge:"+judge);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("judge", judge);
	}

	/**
	 * 查询店铺并分页
	 * @param current 当前页数
	 * @return
	 */
	@GetMapping("/pageShop")
	public WebResult pageShop(@RequestParam(defaultValue = "1",required = false) int current){
		//分页查询 默认五条 不需要条件
		//Page（页数，分页条数）
		Page<Shop> page = new Page<Shop>(current,10);
		Page<Shop> shopPage = iShopService.page(page, null);
		System.out.println("---------------------注意打印值-----------------------");
		shopPage.getRecords().forEach(System.out::println);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("shop", shopPage);
	}

	/**
	 *
	 * @param id
	 * @param shopName
	 * @param current
	 * @return
	 */
	@GetMapping("likeShop")
	@Cacheable(value = "like_shop", unless = "#request == null ")
	public WebResult likeShop(@RequestParam(defaultValue = "0",required = false) int id, String shopName,@RequestParam(defaultValue = "1",required = false) int current){
		//按条件模糊查询
		//Page（页数，分页条数）
		Page<Shop> page = new Page<>(current,10);
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("state", "2");
		if(id != 0){
			queryWrapper.eq("id", id);
		}
		if(StringUtils.hasText(shopName)){
			queryWrapper.likeRight("shop_name", shopName);
		}
		Page<Shop> shopPage = iShopService.page(page, queryWrapper);

		return new WebResult(WebResultMsgCode.SUCCESS).putData("shop", shopPage);
	}

	@GetMapping("/getAuditShopInfo")
	@Cacheable(value = "get_audit_shop_info", unless = "#request == null ")
	public WebResult getAuditShopInfo(int shopId){
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", shopId);
		Shop shop = iShopService.getOne(queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("shop", shop);
	}

	@PostMapping("/auditShopOK")
	public WebResult auditShopOK(@RequestParam Integer shopId){
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", shopId);
		Shop shop = new Shop();
		shop.setState("0");
		boolean judge = iShopService.update(shop,queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("judge", judge);
	}

	/**
	 * 上传头像, 修改头像
	 * @param file 文件上传工具类
	 * @param request http请求
	 * @return
	 */
	@PostMapping("/upload/avatar")
	public WebResult uploadHeadUrl(@RequestParam("file") MultipartFile file,
	                               HttpServletRequest request) {
//		log.info("uid:" + getUid(request));
		try {
			byte[] bytes = file.getBytes();
			String fileName = UpFilesNameUtils.getFilesName("img",file.getOriginalFilename());
			//例如:"F:/学习/S2项目图片素材"为本地目录
			//路径要引用配置文件里的
			Path path = Paths.get(uploadUrl + fileName);
			//将上传图片路径写入文件
			Files.write(path,bytes);

			String imageUrl = prefixUrl + fileName;

			Shop shop = new Shop();
//			user.setId(getUid(request));
			//头像最终路径=图片的服务器路径前缀+图片名称
			shop.setHeadPortrait(imageUrl);
			redisService.setObject("headPortrait", imageUrl);
			//修改用户头像
//			userService.getUpdateUserAvatarByUserId(user);
			//返回文件名字
			log.info(imageUrl);
			return new WebResult(WebResultMsgCode.SUCCESS).putData("filename", imageUrl);
		} catch (IOException e) {
			//e.printStackTrace();7
			log.error("error: "+e.getMessage());
		}
		return new WebResult(WebResultMsgCode.FAIL);
	}


	@GetMapping("getheadPortrait")
	public WebResult getheadPortrait(){
		String headPortrait = redisService.getObject("headPortrait");
		log.info("head:"+headPortrait);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("headPortrait", headPortrait);
	}

	@PostMapping("delRedisShop")
	public void delRedisShop(){
		redisService.delObject("headPortrait");
	}

	@GetMapping("fieryShop")
	@Cacheable(value = "fiery_shop", unless = "#request == null ")
	public WebResult fieryShop(){
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("sales_volume")
				.ne("state", 2);
		List<Shop> list = iShopService.list(queryWrapper);
		return new WebResult(WebResultMsgCode.SUCCESS).putData("list", list);
	}





}
